# -*- coding: utf-8 -*-
# Author     :wang_tuo
# Time       :2021/12/22 16:35

import re
import random

import easyocr
import requests


def get_ua():
    first_num = random.randint(55, 62)
    third_num = random.randint(0, 3200)
    fourth_num = random.randint(0, 140)
    os_type = [
        '(Windows NT 6.1; WOW64)', '(Windows NT 10.0; WOW64)', '(X11; Linux x86_64)',
        '(Macintosh; Intel Mac OS X 10_12_6)'
    ]
    chrome_version = f'Chrome/{first_num}.0.{third_num}.{fourth_num}'

    ua = ' '.join(['Mozilla/5.0', random.choice(os_type), 'AppleWebKit/537.36',
                   '(KHTML, like Gecko)', chrome_version, 'Safari/537.36']
                  )
    return ua


ua_header = lambda: {"User-Agent": get_ua()}

reader = easyocr.Reader(["en"])

warning_url = "https://www.amazon.com/errors/validateCaptcha"  # 出现验证码的url


def parse(url, headers=None, params=None):
    headers = ua_header() if headers is None else headers
    try:
        resp = requests.get(url, headers=headers, params=params)
    except:
        return None
    return resp


# 识别验证码后返回的cookie
def vcode_cookie() -> dict:
    resp = parse(warning_url)
    print("最初响应的cookie {}".format(dict(resp.cookies)))
    html = resp.text
    amzn_value = re.findall('name="amzn".*?value="(.*?)"', html)[0]  # 处理验证码的参数之一
    img_url = re.findall('"(.*?images-na.ssl-images-amazon.com/captcha.*?)"', html)[0]  # 图片验证码的url
    vcode = get_vcode(img_url)
    params = {
        "amzn": amzn_value,
        "amzn-r": "/",
        "field-keywords": vcode,
    }
    headers = {
        "Connection": "keep-alive",
        "sec-ch-ua": '"Chromium";v="94", "Google Chrome";v="94", ";Not A Brand";v="99"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"Windows"',
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
        "Sec-Fetch-Site": "none",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-User": "?1",
        "Sec-Fetch-Dest": "document",
        "Accept-Encoding": "gzip, deflate, br",
    }
    print("出现的验证码 {} 爬虫识别为 {}".format(img_url, vcode))
    resp = parse(warning_url, params=params, headers=headers)
    cookie = dict(resp.cookies)
    if not cookie:
        print("WARNING 验证码识别失败")
        return {}
    print("识别验证码后的cookie {}".format(dict(resp.cookies)))
    return cookie


# 传入图片url，返回验证码
def get_vcode(img_url):
    bdata = parse(img_url).content
    result = reader.readtext(bdata)
    vcode = result[0][1]
    print(vcode)
    return vcode


def t1():
    img_url = "https://images-na.ssl-images-amazon.com/captcha/ddwwidnf/Captcha_dwfvxnappd.jpg"
    img_url = "https://images-na.ssl-images-amazon.com/captcha/xzqdsmvh/Captcha_ebkbxtuidw.jpg"
    get_vcode(img_url)


if __name__ == '__main__':
    vcode_cookie()
